package cn.seaboot.admin.mvc.mask;

import cn.seaboot.commons.core.Converter;
import cn.seaboot.commons.core.DataMaskingUtils;
import cn.seaboot.commons.lang.Symbol;
import cn.seaboot.commons.reflect.FieldAccess;
import cn.seaboot.commons.reflect.ObjectField;

/**
 * 通用对象脱敏工具
 * <p>
 * 基于注解，如果一个对象
 *
 * @author Mr.css
 * @version 2023-06-28 18:12
 */
public class DefaultDesensitization implements ObjectDesensitization {

    /**
     * 处理集合、数组的时候，最好前置判断列表是否需要脱敏
     *
     * @param o 对象实体
     * @return 是否需要脱敏
     */
    public boolean skip(Object o) {
        FieldAccess fieldAccess = FieldAccess.create(o.getClass());
        ObjectField[] fields = fieldAccess.getFields();
        for (ObjectField field : fields) {
            // 字符串，并且包含注解
            if (field.getType() == String.class && field.getAnnotation(DesensitizeProperty.class) == null) {
                return false;
            }
        }
        return true;
    }

    /**
     * 处理数据脱敏
     */
    @Override
    public void process(Object o) {
        FieldAccess fieldAccess = FieldAccess.create(o.getClass());
        ObjectField[] fields = fieldAccess.getFields();
        for (ObjectField field : fields) {
            if (field.getType() == String.class) {
                DesensitizeProperty property = field.getAnnotation(DesensitizeProperty.class);
                if (property != null) {
                    String v = Converter.toString(field.getValue(o));
                    v = DataMaskingUtils.replaceInner(v, property.front(), property.back(), Symbol.ASTERISK);
                    field.setValue(o, v);
                }
            }
        }
    }
}
